package com.daka.auth;

import com.daka.annotation.Login;
//import com.daka.enumerate.StatusCode;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Login login = handlerMethod.getMethodAnnotation(Login.class);
            if (null == login) {
                return true;
            }
            HttpSession session = request.getSession();
            Object userId = session.getAttribute("userId");
            // Did not login yet
            if (null == userId || "".equalsIgnoreCase(userId.toString())) {
                throw new Exception("");
            }

        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        preHandle(request, response, handler);
    }
}